// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  var log = 0;
  var result = new Array();

  const days = await db.collection('location').where({
    user_id: wxContext.OPENID,
  }).count();

  //通过JS的方法获取当前年月日
  var date = new Date();
  date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
  //获取年份  
  const Y = date.getFullYear();
  //获取月份  
  const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  //获取当日日期 
  const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  let today = await db.collection('location').where({
    user_id: wxContext.OPENID,
    time: {
      year: Y,
      month: M,
      day: D,
    }
  }).get();

  if ((days.total == 0) || (days.total == 1 && today.data[0] != null)) {
    log = 1;
    result = new Array();
    return {
      _log: log,
      words: result,
    }
  }
  if ((days.total == 2 && today.data[0] != null) || (days.total == 1 && today.data[0] == null)) { //
    log = 2;
    result = new Array();
    const yes = await cloud.callFunction({ //上次背单词的信息
      // 要调用的云函数名称
      name: 'last',
      // 传递给云函数的参数
      data: {
        openid: wxContext.OPENID,
      }
    });

    for (let i = 1; i <= yes.result.word_id; i++) {
      let word = await db.collection('word').where({
        word_id: i,
      }).get();
      result.push(word.data[0]);
    }
    return {
      _log: log,
      words: result,
    }
  } else { // 今天至少第三次背单词了

    const yes = await cloud.callFunction({ //上次背单词的信息
      // 要调用的云函数名称
      name: 'last',
      // 传递给云函数的参数
      data: {
        openid: wxContext.OPENID,
      }
    });
    var yes_word_id = yes.result.word_id;
    //上次背单词的日期
    var yestoday = new Date(yes.result.time.year + "/" + yes.result.time.month + "/" + yes.result.time.day);
    //上上次背单词的情况
    let yes_Y = 0;
    let yes_M = "";
    let yes_D = 0;
    var _yes = null;
    while (true) {
      yestoday = new Date(yestoday.setTime(yestoday.getTime() - 24 * 60 * 60 * 1000));
      //获取?年份  
      yes_Y = yestoday.getFullYear();
      //获取?月份  
      yes_M = (yestoday.getMonth() + 1 < 10 ? '0' + (yestoday.getMonth() + 1) : yestoday.getMonth() + 1);
      //获取?日期 
      yes_D = yestoday.getDate() < 10 ? '0' + yestoday.getDate() : yestoday.getDate();
      _yes = await db.collection('location').where({
        user_id: wxContext.OPENID,
        time: {
          year: yes_Y,
          month: yes_M,
          day: yes_D,
        }
      }).get();
      if (_yes.data[0] != null) break;
    }
    var first = _yes.data[0].word_id + 1;
    //yes_word_id & first √ 接下来找前14天背的单词 目前yestoday是上上次背单词的日期
    var before14 = 1;

    for (let i = 0; i < 14; i++) {
      yestoday = new Date(yestoday.setTime(yestoday.getTime() - 24 * 60 * 60 * 1000));
      //获取?年份  
      yes_Y = yestoday.getFullYear();
      //获取?月份  
      yes_M = (yestoday.getMonth() + 1 < 10 ? '0' + (yestoday.getMonth() + 1) : yestoday.getMonth() + 1);
      //获取?日期 
      yes_D = yestoday.getDate() < 10 ? '0' + yestoday.getDate() : yestoday.getDate();

      _yes = await db.collection('location').where({ //yes：昨天的数据
        time: {
          year: yes_Y,
          month: yes_M,
          day: yes_D,
        }
      }).get();
      if (_yes.data[0] != null) {
        before14 = _yes.data[0].word_id;
      }
    }

    //三个数据全了，下面分类讨论  
    var words_id1 = new Array();
    var words_id2 = new Array();
    if (yes_word_id - before14 + 1 < event.num) {
      //返回之前学的
      log = 3;
      for (let i = before14; i <= yes_word_id; i++) {
        let word = await db.collection('word').where({
          word_id: i,
        }).get();
        result.push(word.data[0]);
      }
    } else if (yes_word_id - first + 1 >= event.num) {
      if (first - before14 < event.num / 5) {
        //return array2.all + array1.random
        var array2Length = first - before14;
        var array1Length = event.num - array2Length;
        log = 4;

        //将array2全部放进去
        for (let i = before14; i < first; i++) {
          let word = await db.collection('word').where({
            word_id: i,
          }).get();
          result.push(word.data[0]);
        }
        //word_id1 用来存放上次复习所有单词的id
        for (let i = first; i <= yes_word_id; i++) {
          words_id1.push(i);
        }
        var return_array = new Array();
        for (let i = 0; i < array1Length; i++) {
          //判断如果数组还有可以取出的元素,以防下标越界
          if (words_id1.length > 0) {
            //在数组中产生一个随机索引
            var arrIndex = Math.floor(Math.random() * words_id1.length);
            //将此随机索引的对应的数组元素值复制出来
            return_array[i] = words_id1[arrIndex];
            //然后删掉此索引的数组元素,这时候temp_array变为新的数组
            words_id1.splice(arrIndex, 1);
          } else {
            //数组中数据项取完后,退出循环,比如数组本来只有10项,但要求取出20项.
            break;
          }
        }

        //return_array 为随机抽出出来的word_id 
        while (return_array.length != 0) {
          let word = await db.collection('word').where({
            word_id: return_array.pop(),
          }).get();
          result.push(word.data[0]);
        }
      } else {

        //return array1 * 4/5 + array2 * 1/5
        var array1Length = event.num / 5 * 4;
        var array2Length = event.num - array1Length;
        log = 5;
        //word_id1 用来存放上次复习所有单词的id
        for (let i = first; i <= yes_word_id; i++) {
          words_id1.push(i);
        }
        //word_id2 用来存放14天前的单词id
        for (let i = before14; i < first; i++) {
          words_id2.push(i);
        }

        var return_array = new Array();
        for (let i = 0; i < array2Length; i++) {
          if (words_id2.length > 0) {
            var arrIndex = Math.floor(Math.random() * words_id2.length);
            return_array[i] = words_id2[arrIndex];
            words_id2.splice(arrIndex, 1);
          } else {
            break;
          }
        }
        //return_array 为随机抽出出来的word_id 
        while (return_array.length != 0) {
          let word = await db.collection('word').where({
            word_id: return_array.pop(),
          }).get();
          result.push(word.data[0]);
        }

        var return_array = new Array();
        for (let i = 0; i < array1Length; i++) {
          if (words_id1.length > 0) {
            var arrIndex = Math.floor(Math.random() * words_id1.length);
            return_array[i] = words_id1[arrIndex];
            words_id1.splice(arrIndex, 1);
          } else {
            break;
          }
        }
        //return_array 为随机抽出出来的word_id 
        while (return_array.length != 0) {
          let word = await db.collection('word').where({
            word_id: return_array.pop(),
          }).get();
          result.push(word.data[0]);
        }
      }
    } else {
      //return array1.all+array2.random
      var array1Length = yes_word_id - first + 1;
      var array2Length = event.num - array1Length;
      log = 6;
      //array2 随机
      //word_id2 用来存放14天前的单词id
      for (let i = before14; i < first; i++) {
        words_id2.push(i);
      }
      var return_array = new Array();
      for (let i = 0; i < array2Length; i++) {
        if (words_id2.length > 0) {
          var arrIndex = Math.floor(Math.random() * words_id2.length);
          return_array[i] = words_id2[arrIndex];
          words_id2.splice(arrIndex, 1);
        } else {
          break;
        }
      }
      //return_array 为随机抽出出来的word_id 
      while (return_array.length != 0) {
        let word = await db.collection('word').where({
          word_id: return_array.pop(),
        }).get();
        result.push(word.data[0]);
      }
      //array1.all
      for (let i = first; i <= yes_word_id; i++) {
        let word = await db.collection('word').where({
          word_id: i,
        }).get();
        result.push(word.data[0]);
      }
    }
  }

  return {
    _log: log,
    words: result,
  }
}